<template>
  <div class="goods-bg">
    <div class="app-container goods-search" id="search">
      <!-- 类别组件catagory -->
      <catagory :catagorys="classify" :number="totalCount" v-model="param.goodsPro" @set="setClassifyList"></catagory>
      <!-- 排序组件 -->
      <div class="ma10">
        <order-by :list="channelList" v-if="channelList && channelList.length" :selected="false" :init-param="param" :orderby="param.orderBy" :ordertype="param.orderType" :minprice="param.goodsCurrentPriceFloor" :maxprice="param.goodsCurrentPriceCeiling" @on-change="fetchSearchGoodsByParams"></order-by>
      </div>
      <!-- 商品列表 -->
      <div class="mt14">
        <!-- 遍历商品详情 -->
        <div class="goods-container fl" :class="{'no-margin': (index + 1) % 5 == 0}" v-for="(goods, index) in allSearchResult" :key="index">
          <goods-item :goods="goods"></goods-item>
        </div>
        <div class="mb6 fl bgImg" v-show="allSearchResult.length == 0"></div>
        <!-- 分页 -->
        <w-paging class="paging" v-show="totalPage > 1" :current="param.currentPage" :total="totalPage" @on-page="getNextPageData"></w-paging>
        <div class="clear"></div>
      </div>
    </div>
  </div>
</template>

<script>
  // 导入类别组件
  import catagory from './components/Catagory'

  // 排序组件（按照价格，人气等排序）
  import orderBy from './components/OrderBy'

  // 商品组件
  import goodsItem from './components/GoodsItemNew'
  
  import { apiSerachGoods } from 'js/api'
  import { parseQueryString, joinQueryParamsToUrl } from 'js/util'

  export default {
    components: {
      catagory,
      orderBy,
      goodsItem
    },
    data() {
      return {
        catagoryInfo: [],
        goodsInfos: [],
        classifyList: [],
        param: {
          currentPage: parseInt(this.$route.query.page) || 1,
          showCount: 20,
          // 搜索类型 goods：商品 store：店铺 goodsBrand：品牌
          searchType: 'goods',
          // 商品的搜索关键字
          keyWord: this.$route.query.key || '',
          // 品牌名称
          brandName: this.$route.query.name || '',
          // 商品最低价
          goodsCurrentPriceFloor: this.$route.query.pricedown || '',
          // 商品最高价
          goodsCurrentPriceCeiling: this.$route.query.priceup || '',
          // 商家id
          storeId: this.$route.query.sid || '',
          // 商家所在地
          storeArea: '',
          // 主营行业
          mainIndustry: '',
          // 最低年销售额
          yearSalesFloor: '',
          // 最高年销售额
          yearSalesCeiling: '',
          // 一级分类ID
          gcIdFirst: this.$route.query.gf || '',
          // 二级分类ID
          gcIdSecond: this.$route.query.gs || '',
          // 三级分类的关键词
          gcIdThird: this.$route.query.gfh || '',
          // 四级分类的关键词
          gcIdFourth: this.$route.query.gft || '',
          // 根据类目条件搜索
          goodsPro: this.$route.query.p || '',
          // 按那个字段排序
          orderBy: this.$route.query.ob || '',
          // 排序顺序
          orderType: this.$route.query.ot || 'desc',
          goodsType: this.$route.query.gtype,
          aGoods: this.$route.query.ag || '',
          areaId: this.$route.query.ai || '',
          areaName: this.$route.query.an || '',
          tierdPrice: this.$route.query.tp || ''
        },
        classify: [],
        totalPage: 0,
        totalCount: 0,
        allSearchResult: '',
        // 编码
        code: {
          goodsCurrentPriceFloor: 'pricedown',
          goodsCurrentPriceCeiling: 'priceup',
          goodsType: 'gtype',
          aGoods: 'ag',
          areaId: 'ai',
          areaName: 'an',
          tierdPrice: 'tp',
          orderBy: 'ob',
          orderType: 'ot'
        },
        reg: {
          page: /(?![?&])(pricedown)=\w{0,}/gi,
          goodsCurrentPriceFloor: /(?![?&])(pricedown)=\w{0,}/gi,
          goodsCurrentPriceCeiling: /(?![?&])(priceup)=\w{0,}/gi,
          goodsType: /(?![?&])(gtype)=\w{0,}/gi,
          aGoods: /(?![?&])(ag)=\w{0,}/gi,
          areaId: /(?![?&])(ai)=\w{0,}/gi,
          areaName: /(?![?&])(an)=(\w|[^\x00-\xff]){0,}/gi,
          tierdPrice: /(?![?&])(tp)=\w{0,}/gi,
          orderBy: /(?![?&])(ob)=\w{0,}/gi,
          orderType: /(?![?&])(ot)=\w{0,}/gi
        },
        channelList: []
      }
    },
    created() {
      this.fetchSerachGoods()
    },
    watch: {
      $route(to, from) {
        // 路由中搜索关键字改变时，重新请求搜索
        // 当前页
        this.param.currentPage = parseInt(this.$route.query.page) || 1
        // 关键词（宝贝）
        this.param.keyWord = this.$route.query.key
        // 品牌名称（品牌）
        this.param.brandName = this.$route.query.name
        // 最低价
        this.param.goodsCurrentPriceFloor = this.$route.query.pricedown
        // 最高价
        this.param.goodsCurrentPriceCeiling = this.$route.query.priceup
        // 排序方式
        this.param.orderBy = this.$route.query.ob
        this.param.orderType = this.$route.query.ot
        this.param.goodsPro = this.$route.query.p
        // 店铺id
        this.param.storeId = this.$route.query.sid
        // 一级导航菜单搜索
        this.param.gcIdFirst = this.$route.query.gf
        // 二级导航菜单搜索
        this.param.gcIdSecond = this.$route.query.gs
        // 二级导航菜单搜索
        this.param.gcIdThird = this.$route.query.gfh
        // 四级分类的关键词
        this.param.gcIdFourth = this.$route.query.gft
        // 商品类型（1：伙拼商品）
        this.param.goodsType = this.$route.query.gtype
        // 增值商品
        this.param.aGoods = this.$route.query.ag
        // 地区id
        this.param.areaId = this.$route.query.ai
        // 地区名称
        this.param.areaName = this.$route.query.an
        // 价格
        this.param.tierdPrice = this.$route.query.tp
        // 将分页重置为1
        this.param.currentPage = parseInt(this.$route.query.page || '1')
        // 查询数据
        this.fetchSerachGoods()
      }
    },
    methods: {
      // 获取商品搜索列表
      fetchSerachGoods() {
        // 清空商品搜索结果
        this.allSearchResult = []

        // 清空商品分类
        this.classify = []
        // 请求接口
        apiSerachGoods(this.param).then((data) => {
          // 搜索结果
          this.allSearchResult = data.luceneList

          // 当前页
          this.param.currentPage = data.currentPage

          // 当前选中的数据
          this.channelList = data.channel

          // 总页码
          this.totalPage = data.totalPage

          // 总数量
          this.totalCount = data.totalCount

          // 商品分类
          this.classify = data.goodsPropertyList
        })
      },

      /**
       * 排序组件中输入的值去查询接口
       *
       * @param { Object } params 排序组件中输入的参数
       */
      fetchSearchGoodsByParams(params) {
        let queryParams = parseQueryString(this.$route.fullPath)
        // 将选中的值塞到路由中
        for (let key in params) {
          queryParams[this.code[key]] = params[key]
        }
        this.$router.push(decodeURIComponent(encodeURIComponent(joinQueryParamsToUrl(this.$route.fullPath, queryParams))))
      },

      /**
       * 设置排序
       *
       * @params { String } val 排序字段
       */
      setOrderBy(val) {
        // 如果当前是非综合排序
        this.param.orderBy = val
        // 路由中替换排序类别的搜索条件
        let fullPath = this.$route.fullPath.replace(/(?![?&])(ob)=\w{0,}/gi, `ob=${this.param.orderBy}`)
        this.$router.push(decodeURIComponent(encodeURIComponent(fullPath)))
      },

      /**
       * 设置排序方式
       *
       * @params { String } val 排序方式（升序，降序）
       */
      setOrderType(val) {
        let newSearch = ''
        // 初始化为第一页
        this.param.currentPage = 1

        // 如果当前是非综合排序
        this.param.orderType = val

        // 路由中添加排序升降的搜索条件
        let fullPath = this.$route.fullPath.split('&ot')[0]
        newSearch = `${fullPath}&ot=${this.param.orderType}`
        this.$router.push(decodeURIComponent(encodeURIComponent(newSearch)))
      },

      /**
       * 设置价格
       *
       * @params { Object } price 价格对象
       */
      setPrice(price) {
        let newSearch = ''
        // 初始化为第一页
        this.param.currentPage = 1

        // 设置最低价格
        this.param.goodsCurrentPriceFloor = price.min

        // 设置最高价格
        this.param.goodsCurrentPriceCeiling = price.max

        // 路由中添加排序升降的搜索条件
        let fullPathDown = this.$route.fullPath.split('&pricedown')[0]
        // let fullPathUp = this.$route.fullPath.split('&priceup')[0]
        newSearch = `${fullPathDown}&pricedown=${this.param.goodsCurrentPriceFloor}&priceup=${this.param.goodsCurrentPriceCeiling}`
        this.$router.push(decodeURIComponent(encodeURIComponent(newSearch)))
        // 执行搜索功能
        // this.fetchSerachGoods()
      },

      /**
       * 获取下一页数据
       *
       * @params { Number } page 当前页码
       */
      getNextPageData(page) {
        // 设置当前页码
        this.param.currentPage = page
        // 路由中添加--分页
        let searchPage = this.$route.fullPath.split('&page')[0]
        let fullPath = `${searchPage}&page=${this.param.currentPage}`
        this.$router.push(decodeURIComponent(encodeURIComponent(fullPath)))
      },

      /**
       * 将选中的分类，查询数据
       */
      setClassifyList(value) {
        // 路由中添加排序升降的搜索条件
        let queryParams = parseQueryString(this.$route.fullPath)
        // 将选中的值塞到路由中
        queryParams['p'] = value
        this.$router.push(decodeURIComponent(encodeURIComponent(joinQueryParamsToUrl(this.$route.fullPath, queryParams))))
      }
    }
  }
</script>
<style lang="scss">
  .goods-bg {
    .m-paging {
      margin: 50px 0 0 !important;
    }
  }
</style>
<style lang="scss" scoped>
  @import '../../scss/_var.scss';
  .goods-bg {
    background-color: $color-white;
    margin-top: -10px;
    margin-bottom: -45px;
    border-bottom: 1px solid #CCCCCC;
    padding-bottom: 50px;

    .goods-container {
      margin-right: 12px;
      margin-bottom: 12px;

      &.no-margin {
        margin-right: 0px;
      }
    }
  }
  .goods-search {
    border-top: 1px solid #ccc;
    margin-top: 10px;
  }
  .ma10 {
    margin: 10px 0px;
  }
  .mt14 {
    margin-top: 14px;
  }
  .mr6 {
    margin-right: 6px;
  }
  .mb6 {
    margin-bottom: 6px;
  }
  .fl {
    float: left;
  }
  .clear {
    clear: both;
  }
  .search-number {
    color: #999999;
    margin: 18px 0px 22px 0px;
  }
  .paging {
    float: left;
    width: 100%;
  }
  .bgImg {
    background-image: url(/static/img/icon_null.45ca649.png);
    margin: 50px auto auto;
    width: 100%;
    height: 420px;
    background-repeat: no-repeat;
    text-align: center;
    background-size: contain;
    background-position: 50% 50%;
  }
</style>